package com.charles.seckillAuth.service;

import com.charles.seckillData.domain.SysUser;
import com.charles.seckillData.feignService.RemoteUserService;
import com.charles.seckillData.model.UserLogin;
import com.charles.seckillComponentCommon.constants.RoleConstants;
import com.charles.seckillComponentCommon.domain.R;
import com.charles.seckillComponentCommon.exceptions.ServiceException;
import com.charles.seckillComponentCommon.utils.BcryptUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author Charles-H
 * 
 * 注册业务
 */
@Component
public class SysRegisterService {
    
    @Autowired
    private RemoteUserService remoteUserService;
    
    public void register(String username, String userCard, String password, Integer age,  String sex) {
        if (username.isEmpty() || userCard.isEmpty() || password.isEmpty()) {
            throw new ServiceException("请完善信息");
        }

        R<UserLogin> result = remoteUserService.queryUserInfoByUserCard(userCard, "inner");
        
        if (result.getCode().equals(R.SUCCESS)) {
            throw new ServiceException("该身份证号码已存在");
        }
        
        SysUser user = new SysUser();
        
        // 这里可以自行添加权限，为了方便，我直接用他们id，一般是需要根据权限名字调用roleId的
        // 1:admin,2:common,3:underage,4:nojob,5:discredit,6:debt
        if (age < 18) {
            user.setRole_id(3);
        } else {
            user.setRole_id(2);
        }
        user.setUser_name(username);
        user.setUser_card(userCard);
        user.setPassword(BcryptUtil.hashPassword(password));
        user.setAge(age);
        user.setSex(sex);
        
        // 远程注册
        R<Boolean> registerResult = remoteUserService.registerUser(user, RoleConstants.INNER);
        
        if (registerResult.getCode().equals(R.FAIL)) {
            throw new ServiceException(registerResult.getMsg());
        }

    }
    
}
